package com.rem.chat.common.utils;

import cn.hutool.crypto.digest.DigestUtil;
import com.rem.chat.common.constants.Constants;
import com.rem.chat.common.errcode.ServiceErrorCodeConstants;
import com.rem.chat.common.exception.ServiceException;
import com.rem.chat.service.enums.UserContactTypeEnum;
import org.apache.commons.lang3.RandomStringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.util.StringUtils;

import java.util.Arrays;

/**
 * @author: Themberfue
 * @date: 2025/6/4 14:52
 * @description:
 */
public class StringUtil {
    public static String encodeSHA256(String data) {
        if (!StringUtils.hasLength(data)) {
            throw new ServiceException(ServiceErrorCodeConstants.ENCODE_DATA_IS_NULL);
        }
        return DigestUtil.sha256Hex(data);
    }

    public static String encodeMD5(String data) {
        if (!StringUtils.hasLength(data)) {
            throw new ServiceException(ServiceErrorCodeConstants.ENCODE_DATA_IS_NULL);
        }
        return DigestUtil.md5Hex(data);
    }

    public static String getUserId() {
        return UserContactTypeEnum.USER.getPrefix() +
                getRandomNumber(Constants.USER_ID_LENGTH_11);
    }

    public static String getGroupId() {
        return UserContactTypeEnum.GROUP.getPrefix() +
                getRandomNumber(Constants.USER_ID_LENGTH_11);
    }

    // ! 确保没有前导零
    public static String getRandomNumber(Integer count) {
        // Step 1. 生成第一位数字 (1-9)
        String firstDigit = RandomStringUtils.random(1, false, true);
        while (firstDigit.equals("0")) {
            firstDigit = RandomStringUtils.random(1, false, true);
        }

        // Step 2. 生成剩余的数字 (0-9)
        String remainingDigits = RandomStringUtils.random(count - 1, false, true);
        return firstDigit + remainingDigits;
    }

    public static String getRandomString(Integer count) {
        return RandomStringUtils.random(count, true, false);
    }

    public static String cleanHTMLTag(String content) {
        if (!StringUtils.hasText(content)) {
            return content;
        }
        // Step 1. 清理所有 HTML标签，只保留文本内容
        String cleanText = Jsoup.clean(content, Safelist.none());

        // Step 2. 将换行符转换为 <br>
        return cleanText.replace("\r\n", "<br>")
                .replace("\n", "<br>");
    }

    public static String getSessionId(String[] userIds) {
        Arrays.sort(userIds);
        return encodeMD5(org.apache.commons.lang3.StringUtils.join(userIds, ""));
    }

    public static String getFileSuffix(String originalFilename) {
        if (!StringUtils.hasText(originalFilename)) {
            return null;
        }
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    public static boolean isNumber(String fileId) {
        if (!StringUtils.hasText(fileId)) {
            return false;
        }
        String pattern = "^[0-9]+$";
        return fileId.matches(pattern);
    }
}
